#!/usr/bin/env bash

rubygems_detect_ruby_lib_gem_path_from()
{
  ruby_lib_gem_path="$( __rvm_ruby_config_get ${1}prefix "$ruby_path" )" || ruby_lib_gem_path=""
  [[ -z "${ruby_lib_gem_path:-}" ]] ||
  {
    ruby_lib_gem_path="$( __rvm_ruby_config_get ${1}dir  "$ruby_path" )" || ruby_lib_gem_path=""
    ruby_lib_gem_path="${ruby_lib_gem_path%/*}"
  }
  [[ -n "${ruby_lib_gem_path:-}"    ]] || return 1
  [[ -d "${ruby_lib_gem_path}/gems" ]] || return 2
}

rubygems_detect_ruby_lib_gem_path_fallback()
{
  rubygems_detect_ruby_lib_gem_path_from "rubylib" ||
  rubygems_detect_ruby_lib_gem_path_from "lib"     ||
  return $?

  ruby_lib_gem_path+="/gems"

  \typeset ruby_version
  ruby_version="$( __rvm_ruby_config_get ruby_version "$ruby_path")" || ruby_version=""
  if
    [[ -n "${ruby_version:-}" && -d "${ruby_lib_gem_path}/${ruby_version:-}" ]]
  then
    ruby_lib_gem_path+="$ruby_version"
  elif
    [[ -d "${ruby_lib_gem_path}/shared" ]]
  then
    ruby_lib_gem_path+="shared"
  else
    return 3
  fi
}

rubygems_detect_ruby_lib_gem_path()
{
  \typeset ruby_path
  ruby_path="$( __rvm_which "${1:-ruby}" )" ||
  {
    rvm_error "Missing 'ruby' in 'rubygems_detect_ruby_lib_gem_path'."
    return 1
  }

  ruby_lib_gem_path="$(
    unset GEM_HOME GEM_PATH
    "$ruby_path" -rrubygems -e 'puts Gem.default_dir' 2>/dev/null
  )" || ruby_lib_gem_path=""

  [[ -n "$ruby_lib_gem_path" ]] ||
  rubygems_detect_ruby_lib_gem_path_fallback ||
  return $?
}
